package Aleehot100;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: c047
 * Package: Aleehot100
 * Description: 105. 从前序与中序遍历序列构造二叉树
 *
 * @Author BCXJ
 * @Create 2025/7/17 08:57
 * @Version 1.0
 * @Since 1.0
 */
public class c047 {

    public static void main(String[] args) {
//        System.out.println(null == 0);
        int[] preOrder = {3,9,20,15,7};
        int[] inOrder = {9,3,15,20,7};
        System.out.println(buildTree(preOrder, inOrder));
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    static Map<Integer, Integer> map = new HashMap<>(); // 记录中序的每一个元素的下标
    public static TreeNode buildTree(int[] preorder, int[] inorder) {

        if(preorder == null || inorder == null || preorder.length != inorder.length) {
            return null;
        }
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return process(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    private static TreeNode process(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {
        if (l1 > r1) { // 可以带入 中序·2 1 先序 1 2的例子
            return null;
        }
        TreeNode node = new TreeNode(preorder[l1]);
        Integer index = map.get(preorder[l1]);
        TreeNode left = process(preorder, l1 + 1, l1 + index - l2, inorder, l2, index - 1);
        TreeNode right = process(preorder, l1 + index - l2 + 1, r1, inorder, index + 1, r2);
        node.left = left;
        node.right = right;
        return node;
    }

    /*
            static HashMap<Integer, Integer> map = new HashMap<>();

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null || preorder.length != inorder.length) {
            return null;
        }

        // 构建二叉树
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }

        return process(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    private static TreeNode process(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {
        System.out.println(l1 + " " + r1 + " " + l2 + " " + r2);
        if (l1 > r1) { // 可以带入 中序·2 1 先序 1 2的例子
            return null;
        }
        if (l1 == r1) {
            return new TreeNode(preorder[l1]);
        }
        TreeNode root = new TreeNode(preorder[l1]);
        Integer inIndex = map.get(preorder[l1]);

        root.left = process(preorder, l1 + 1, l1 + inIndex - l2, inorder, l2, inIndex - 1);
        root.right = process(preorder, l1 + inIndex - l2 + 1, r1, inorder, inIndex + 1, r2);

        return root;
    }

     */
}
